import yaml
import os
import sys

PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(PROJECT_ROOT)

from conf.setting import FILE_PATH,DIR_PATH

def get_testcase_yaml(file):
    """
    获取yaml文件的数据
    :param file:yaml文件的路径
    """
    try:
        with open(file,'r',encoding='utf-8') as f:
            yaml_data=yaml.safe_load(f)
            return yaml_data
    except Exception as e:
        print(e)

class ReadYamlData:
    # 读取yaml数据，以及写入数据到yaml文件

    def __init__(self,yaml_file=None):
        if yaml_file is not None:
            self.yaml_file = yaml_file
        else:
            self.yaml_file = 'login.yaml'

    def write_yaml_data(self,value):
        """
        写入数据到yaml文件
        value:(dict)写入的数据
        """ 
        file_path = FILE_PATH['extract'] 
        if not os.path.exists(file_path):
            os.system(file_path)

        try:            
            with open(file_path,'a',encoding='utf-8') as file:
                if isinstance(value,dict):
                    write_data=yaml.dump(value,allow_unicode=True,sort_keys=False)
                    file.write(write_data)
                else:
                    print('写入到【extract.yaml】的数据必须为字典类型！')
        except Exception as e:
            print(e)

    def get_extract_yaml(self,node_name,sec_node_name=None):
        """
        读取接口提取的变量值
        node_name:yaml文件的key值
        """
        file_path=FILE_PATH['extract']

        if os.path.exists(file_path):
            pass
        else:
            print('extract.yaml不存在')

        try:
            with open(file_path,'r',encoding='utf-8') as rf:
                extract_data=yaml.safe_load(rf)
                if sec_node_name is None:
                    return extract_data[node_name]
                else:
                    return extract_data[node_name][sec_node_name]
        except Exception as e:
           print(e)

    def clear_yaml_data(self):
        # 清空extract.yaml文件的数据
        with open(FILE_PATH['extract'],'w') as f:
            f.truncate()

            

# python常用的数据类型：str list dict set tuple
# json序列化和反序列化
# json序列化，就是将字典类型转换成字符串类型
# json_str = json.dump(res,ensure_ascii=False)
# json反序列化，就是将字符串类型转换成字典类型
# json_dict = json.loads(json_str)